﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;
using System.Xml;
using System.Globalization;

namespace AmiEmuLib
{
    public struct MemorySize : IComparable
    {
        private uint m_size;

        public MemorySize(uint a_size)
        {
            m_size = a_size;
        }

        public MemorySize(String a_size)
        {
            m_size = MemorySize.ToValue(a_size);
        }

        public static implicit operator uint(MemorySize a_size)
        {
            return a_size.m_size;
        }

        public static implicit operator MemorySize(uint a_size)
        {
            return new MemorySize(a_size);
        }

        public static implicit operator MemorySize(string a_size)
        {
            return new MemorySize(a_size);
        }

        public override string ToString()
        {
            if (m_size == 0)
                return "0";
            else if (m_size % Consts.MB == 0)
                return String.Format("{0}MB", m_size / Consts.MB);
            else if (m_size % Consts.MB == Consts.MB / 2)
                return String.Format("{0}.5MB", m_size / Consts.MB);
            else if (m_size % Consts.KB == 0)
                return String.Format("{0}KB", m_size / Consts.KB);
            else
                return m_size.ToString();
        }

        private static uint ToValue(String a_size)
        {
            a_size = a_size.Replace(',', '.');

            if (a_size.EndsWith("MB"))
            {
                return (uint)(Single.Parse(a_size.Replace("MB", ""),
                    CultureInfo.InvariantCulture) * Consts.MB);
            }
            else if (a_size.EndsWith("KB"))
            {
                return (uint)(Single.Parse(a_size.Replace("KB", ""),
                    CultureInfo.InvariantCulture) * Consts.KB);
            }
            else
                return UInt32.Parse(a_size);
        }

        int IComparable.CompareTo(object a_obj)
        {
            if (!(a_obj is MemorySize))
                return -1;

            MemorySize mem_size = (MemorySize)a_obj;

            return (int)((long)m_size - (long)mem_size);
        }
    }
}
